package com.opages.mvc.common.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 环境配置初始化
 */
public class EnvironmentContextListener implements ServletContextListener {
    public static String WEBROOTPATH;
    public static String CONTEXTPATH;
    public static String APPID;
    public static String APPNAME;


    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();

        context.setAttribute("ctx", context.getContextPath());

        // context.getRealPath("/"); 有相对路径的问题
        String path = this.getClass().getClassLoader().getResource("/").getPath();
        try {
            path = URLDecoder.decode(path, "UTF-8");
        } catch (Exception e) {
            path = context.getRealPath("/");
        }
        File file = new File(path);
        WEBROOTPATH = file.getParentFile().getParentFile().getAbsolutePath() + File.separator;
        CONTEXTPATH = context.getContextPath();
        APPID = context.getInitParameter(WebUtils.WEB_APP_ROOT_KEY_PARAM);
        APPNAME = context.getServletContextName();

        System.setProperty("user.dir", file.getParentFile().getAbsolutePath() + File.separator);

        String environmentLocation = context.getInitParameter("environmentLocation");
        if (StringUtils.isBlank(environmentLocation)) {
            context.log("未配置环境加载路径");
            System.exit(11);
        }
        try {
            loadProperties(context, WEBROOTPATH + environmentLocation);
        } catch (Exception e) {
            context.log("加载配置文件失败", e);
            e.printStackTrace();
            System.exit(12);
        }


    }

    @SuppressWarnings("unchecked")
    public static void loadProperties(ServletContext context, String filePath) throws Exception {

        context.log("加载配置文件：" + filePath);
        InputStreamReader is = null;
        try {
            Properties properties = new Properties();
            is = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
            properties.load(is);

            Enumeration<String> names = (Enumeration<String>) properties.propertyNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                String value = properties.getProperty(name);
                if (System.getProperties().contains(name)) {
                    String cached = System.getProperty(name);
                    context.log("替换已存在的属性[" + name + "]老值[" + cached + "]新值[" + value + "]");
                } else {
                    context.log("设置属性[" + name + "]值[" + value + "]");
                }
                System.setProperty(name, value);
            }
        } finally {
            is.close();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }
}
